#!/bin/bash

# Tomcat部署脚本
# 用法: ./scripts/deploy-tomcat.sh [tomcat_path]

set -e  # 遇到错误立即退出

echo "🚀 开始部署到Tomcat..."
echo ""

# 1. 构建项目
echo "📦 步骤1: 构建生产版本..."
pnpm run build

if [ $? -ne 0 ]; then
    echo "❌ 构建失败！"
    exit 1
fi

echo "✅ 构建完成"
echo ""

# 2. 复制WEB-INF
echo "📋 步骤2: 复制WEB-INF配置..."
mkdir -p dist/WEB-INF
cp public/WEB-INF/web.xml dist/WEB-INF/

if [ ! -f dist/WEB-INF/web.xml ]; then
    echo "❌ web.xml复制失败！"
    exit 1
fi

echo "✅ WEB-INF配置已复制"
echo ""

# 3. 创建WAR包
echo "📦 步骤3: 创建WAR包..."
cd dist

# 检查是否安装了jar命令
if ! command -v jar &> /dev/null; then
    echo "⚠️  jar命令未找到，尝试使用zip..."
    if command -v zip &> /dev/null; then
        zip -r ../todo.war *
    else
        echo "❌ 请安装JDK或zip工具"
        exit 1
    fi
else
    jar -cvf ../todo.war * > /dev/null 2>&1
fi

cd ..

if [ ! -f todo.war ]; then
    echo "❌ WAR包创建失败！"
    exit 1
fi

WAR_SIZE=$(du -h todo.war | cut -f1)
echo "✅ WAR包创建成功 (大小: $WAR_SIZE)"
echo ""

# 4. 部署到Tomcat（可选）
if [ -n "$1" ]; then
    TOMCAT_HOME="$1"
    
    if [ ! -d "$TOMCAT_HOME" ]; then
        echo "❌ Tomcat目录不存在: $TOMCAT_HOME"
        exit 1
    fi
    
    echo "📤 步骤4: 部署到Tomcat..."
    echo "   Tomcat路径: $TOMCAT_HOME"
    
    # 停止Tomcat（如果正在运行）
    if [ -f "$TOMCAT_HOME/bin/shutdown.sh" ]; then
        echo "   停止Tomcat..."
        "$TOMCAT_HOME/bin/shutdown.sh" > /dev/null 2>&1 || true
        sleep 3
    fi
    
    # 删除旧的部署
    if [ -d "$TOMCAT_HOME/webapps/todo" ]; then
        echo "   删除旧的部署..."
        rm -rf "$TOMCAT_HOME/webapps/todo"
    fi
    
    if [ -f "$TOMCAT_HOME/webapps/todo.war" ]; then
        rm -f "$TOMCAT_HOME/webapps/todo.war"
    fi
    
    # 复制新的WAR包
    echo "   复制WAR包..."
    cp todo.war "$TOMCAT_HOME/webapps/"
    
    # 启动Tomcat
    if [ -f "$TOMCAT_HOME/bin/startup.sh" ]; then
        echo "   启动Tomcat..."
        "$TOMCAT_HOME/bin/startup.sh"
        sleep 2
    fi
    
    echo "✅ 部署完成！"
    echo ""
    echo "🌐 访问地址: http://localhost:8080/todo/"
else
    echo "📤 步骤4: 手动部署"
    echo ""
    echo "WAR包已创建: $(pwd)/todo.war"
    echo ""
    echo "请手动部署："
    echo "  1. 复制 todo.war 到 \$TOMCAT_HOME/webapps/"
    echo "  2. 重启Tomcat"
    echo "  3. 访问 http://localhost:8080/todo/"
    echo ""
    echo "或者运行："
    echo "  ./scripts/deploy-tomcat.sh /path/to/tomcat"
fi

echo ""
echo "✨ 完成！"

